package com.enseirb.bdxmap.activity.task;

import java.util.ArrayList;
import java.util.List;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;

import com.enseirb.bdxmap.activity.MainActivity;
import com.enseirb.bdxmap.activity.listener.MarkerListener;
import com.enseirb.bdxmap.exception.BdxMapException;
import com.enseirb.bdxmap.service.DefibrillatorMarkerService;
import com.enseirb.bdxmap.service.model.DefibrillatorMarkerBO;

public class DefibrillatorTask extends AsyncTask<Void, Integer, List<DefibrillatorMarkerBO>> {
	
	private MarkerListener listener;
	private DefibrillatorMarkerService defibrillatorService = new DefibrillatorMarkerService();
	private ProgressDialog progressDialog;
	private BdxMapException exception = null;
	
	public DefibrillatorTask(MarkerListener listener) {
		this.listener		= listener;
		this.progressDialog = new ProgressDialog((Context)listener);
	}
	
	@Override
	protected void onPreExecute() {
		progressDialog.setIndeterminate(false);
		progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		progressDialog.setCancelable(false);
		progressDialog.setMessage(MainActivity.waitingMessage);
		progressDialog.show();
	}
	
	@Override
	protected List<DefibrillatorMarkerBO> doInBackground(Void... params) {
		List<DefibrillatorMarkerBO> markers = new ArrayList<DefibrillatorMarkerBO>();
		
		try {
			markers = defibrillatorService.getData();
		} catch (BdxMapException e) {
			exception = e;
		}
		return markers;
	}

	@Override
	protected void onPostExecute(List<DefibrillatorMarkerBO> defibrillators) {
		progressDialog.dismiss();
		if(exception != null) {
			listener.printError(exception.getMessage());
		} else {
			listener.printDefibrillatorMarkers(defibrillators);
		}
	}
};
